<?php

require_once (APPLICATION_PATH . '/../library/phpthumblib/ThumbLib.inc.php');

class ProjectController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'project', '');
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $searchtext = "";
        $searchclientstatus = "";
        $searchstatus = "";
        $datefrom = '';
        $dateto = '';
        $orderField = 'prj_id';
        $sort = 'asc';

        /* Pagination Login */
        $itemsPerPageReviews = $this->config->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //Load Customer,Designer and Contractor
        $projectModel = new Model_Project();
        $customerArray = $projectModel->getCustomersArray();
        $desginerArray = $projectModel->getDesignerArray();

        $contractors = $projectModel->getContractorArray();


        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }


        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = "Please select atleast one checkbox";
                }
            }

            /* Search Facility Over Here */
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                if ($searchtype == "prj_name" ||
                        $searchtype == "dsg_name" ||
                        $searchtype == "cus_name") {
                    $searchtext = $postedData["searchtext"];
                    if ($searchtext == '') {
                        $errorMessage[] = "Please enter search text for search.";
                    } else {
                        $where = "$searchtype LIKE '%$searchtext%'";
                    }
                }
            }
        }


        $projectsData = $projectModel->fetchProjects($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        // Total days difference logic
        foreach ($projectsData as $_prj_key => $_project) {
            $projectid = $_project['prj_id'];
            $projectData = $projectModel->fetchEntryById($projectid);
            $project_referecneData = $projectData['PROJECT_REFERENCE'];

            $min_start_date = strtotime('2037-12-12'); //Set an MAximum date initially so can reduce and set minimum one of the date
            $max_end_date = 0; //Maximum End date is set initially a value of zero

            foreach ($project_referecneData as $_prj_ref) {
                $start_date = $_prj_ref['job_startdate'];
                $end_date = $_prj_ref['job_enddate'];
                if ($max_end_date < strtotime($end_date)) {
                    $max_end_date = strtotime($end_date);
                }
                if ($min_start_date > strtotime($start_date)) {
                    $min_start_date = strtotime($start_date);
                }
            }
            $projectsData[$_prj_key]['minimum_start_date'] = date('Y-m-d', $min_start_date); //Minimum Start Date set in the project Array
            $projectsData[$_prj_key]['maximum_end_date'] = date('Y-m-d', $max_end_date); //Maximum End Date set in the project Array
            $day_difference = GTL_Common::getDateDifference($projectsData[$_prj_key]['maximum_end_date'], $projectsData[$_prj_key]['minimum_start_date']);
            $projectsData[$_prj_key]['total_day_diff'] = $day_difference;
            
            //Calculate the total days remaining
            if (strtotime($projectsData[$_prj_key]['maximum_end_date']) > strtotime(date('Y-m-d'))) {
                $day_remaining = GTL_Common::getDateDifference($projectsData[$_prj_key]['maximum_end_date'], date('Y-m-d'));
            } else {
                $day_remaining = 0;
            }
            $projectsData[$_prj_key]['total_day_remaining'] = $day_remaining;
        }


        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($projectModel->getProjectCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'project', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->projectsData = $projectsData;

        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;




        //Load the customer array for the select box in form 
        $this->view->customerArray = $customerArray;

        //Load the designer array for the select box in form 

        $this->view->desginer = $desginerArray;

        //Load the contractor array for the select box in form 
        $this->view->contractors = $contractors;




        $this->view->statusArray = $projectModel->getStatusArray();
        $this->view->searchtype = $searchtype;
        $this->view->searchtext = $searchtext;

        $indexUrl = $this->view->url(array('controller' => 'index', 'action' => 'index'), null, TRUE);
        $projectUrl = $this->view->url(array('controller' => 'project', 'action' => 'list'), null, TRUE);
        $this->view->breadcrumbs = array($indexUrl => "Home", $projectUrl => "Project", "" => "Project Listing");
    }

    public function deleteAction($ids = Array()) {
        //Load Project Model 
        $projectModel = new Model_Project();

        if ($this->_getParam('prj_id') && $this->_getParam('prj_id') != "") {
            $prj_id = $this->_getParam('prj_id');
            $projectModel->deleteProject(Array($prj_id));
            $this->addSuccessMessage("Project deleted succesfully");
            $this->_helper->redirector('list', 'project', '');
        } else {
            $projectModel->deleteProject($ids);
            $this->addSuccessMessage("Project deleted succesfully");
            $this->_helper->redirector('list', 'project', '');
        }
    }

    public function formAction() {
        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $projectData = Array();
        $projectImages = Array();
        $projectReference = Array();
        $this->view->mode = "Add";
        $total_day_diff = ""; //Total day difference
        $projectNotes = Array();

        //Load project Notes
        $projectNotesModel = new Model_Projectnotes();


        //Load the roles
        $aclModel = new Model_Acl();
        $userRoles = $aclModel->getRoles();
        $this->view->userRoles = $userRoles;

        //Load Project Model
        $projectModel = new Model_Project();

        //Load Project Form
        $projectForm = new Form_ProjectForm();

        //Load the customer array for the select box in form 
        $customerArray = $projectModel->getCustomersArray();



        $projectForm->cus_id->addMultiOptions($customerArray);

        //Load the customer array for the select box in form 
        $desginerArray = $projectModel->getDesignerArray();
        $projectForm->dsg_id->addMultiOptions($desginerArray);

        //Load the status array for the select box in form 
        $statusArray = $projectModel->getStatusArray();
        $projectForm->prj_status->addMultiOptions($statusArray);

        //Load the contractor array for the select box in form 
        $contractors = $projectModel->getContractorArray();

        //Load the commision type for the project
        $commisionTypeArray = $projectModel->getCommisionTypeArray();
        $projectForm->dsg_commision_type->addMultiOptions($commisionTypeArray);

        //Load the image type for the project
        $imageTypeArray = $projectModel->getImageTypeArray();

        //Check for the project Parameter
        $projectData['prj_id'] = $this->_request->getParam('prj_id');
        $prj_id = (!empty($projectData['prj_id'])) ? $projectData['prj_id'] : null;

        if (!empty($prj_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $projectModel->fetchEntryById($prj_id);
            $projectImages = $data['PROJECT_IMAGES'];
            $projectReference = $data['PROJECT_REFERENCE'];

            // Total days difference logic
            $project_referecneData = $projectReference;
            $min_start_date = strtotime('2037-12-12'); //Set an MAximum date initially so can reduce and set minimum one of the date
            $max_end_date = 0; //Maximum End date is set initially a value of zero

            foreach ($project_referecneData as $_prj_ref) {
                $start_date = $_prj_ref['job_startdate'];
                $end_date = $_prj_ref['job_enddate'];
                if ($max_end_date < strtotime($end_date)) {
                    $max_end_date = strtotime($end_date);
                }
                if ($min_start_date > strtotime($start_date)) {
                    $min_start_date = strtotime($start_date);
                }
            }
            $day_difference = GTL_Common::getDateDifference(date('Y-m-d', $max_end_date), date('Y-m-d', $min_start_date));
            $total_day_diff = $day_difference;


            $data = $data['PROJECT'];

            //Load project Notes
            $projectNotes = $projectNotesModel->fetchEntryById($prj_id);
        }

        //Populate form 
        $this->view->form = $projectForm->populate($data);
        $this->view->projectData = $data;


        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$projectForm->isValid($postedData)) {
                $errorMessage = $projectForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {
                    //Project save
                    $projectData['prj_id'] = $prj_id;
                    $projectData['prj_name'] = $postedData['prj_name'];
                    $projectData['dsg_id'] = $postedData['dsg_id'];

                    $projectData['dsg_commision_type'] = $postedData['dsg_commision_type'];
                    if ($postedData['dsg_commision_type'] == 'percentage') {
                        $projectData['dsg_commision_percentage'] = $postedData['dsg_commision_percentage'];
                        $projectData['dsg_commision'] = "";
                        if ($postedData['dsg_commision'] != "") {
                            $projectData['dsg_commision'] = GTL_Common::setNumberFormat($postedData['dsg_commision']);
                        }
                    } else {
                        $projectData['dsg_commision_percentage'] = "";
                        $projectData['dsg_commision'] = "";
                        if ($postedData['dsg_commision'] != "") {
                            $projectData['dsg_commision'] = GTL_Common::setNumberFormat($postedData['dsg_commision']);
                        }
                    }

                    if ($postedData['prj_specialdiscount'] != '') {
                        $projectData['prj_specialdiscount'] = GTL_Common::setNumberFormat($postedData['prj_specialdiscount']);
                    } else {
                        $projectData['prj_specialdiscount'] = '';
                    }


                    if ($postedData['prj_totalday'] != '') {
                        $projectData['prj_totalday'] = $postedData['prj_totalday'];
                    } else {
                        $projectData['prj_totalday'] = '0';
                    }




                    $projectData['prj_costprice'] = GTL_Common::setNumberFormat($postedData['prj_costprice']);
                    $projectData['prj_sellingprice'] = GTL_Common::setNumberFormat($postedData['prj_sellingprice']);
                    $projectData['prj_renovationprice'] = GTL_Common::setNumberFormat($postedData['prj_renovationprice']);

                    $projectData['prj_profit_loss_margin'] = GTL_Common::setNumberFormat($postedData['prj_profit_loss_margin']);

                    $projectData['cus_id'] = $postedData['cus_id'];

                    if ($this->view->mode == "Add") {
                        $projectData['prj_created'] = date('Y-m-d :H:i:s');
                    }
                    $projectData['prj_updated'] = date('Y-m-d :H:i:s');
                    $projectData['prj_status'] = $postedData['prj_status'];
                    $projectData['cus_note'] = $postedData['cus_note'];

                    $prj_id = $projectModel->save($projectData, 'prj_id');

                    //Check condition for edit functionality
                    if (array_key_exists('inventorylist', $postedData)) {
                        //Load Quotation Reference Table
                        $jobRefModel = new Model_Projectreference();

                        //Initialize Project Reference Data
                        $job_idData = $postedData['inventorylist'];
                        $job_qtyData = $postedData['qty'];
                        $job_materialcostData = $postedData['cost'];
                        $job_materialsrpData = $postedData['srp'];
                        $job_uomData = $postedData['uom'];
                        $job_totalmaterialcostData = $postedData['totalcost'];
                        $job_totalmaterialsrpData = $postedData['totalsrp'];
                        $contractorIdData = $postedData['contractor_id'];
                        $job_startdateData = $postedData['job_startdate'];
                        $job_enddateData = $postedData['job_enddate'];
                        $job_remarkData = $postedData['job_desc'];
                        $job_codeData = $postedData['product_material_code'];

                        $prjref_idData = $postedData['prjref_id'];


                        //Load Quotation Reference Table
                        $projectRefModel = new Model_Projectreference();
                        //Delete the Project Reference deleted fields 
                        if ($postedData['hdn_delete_prjref_id'] != '') {
                            $deletePrjRefids = $postedData['hdn_delete_prjref_id'];
                            $projectRefModel->delete("prjref_id in (" . $deletePrjRefids . ")");
                        }


                        $j = 0;
                        foreach ($job_idData as $id) {
                            $jobRefData = Array();


                            if ($prjref_idData[$j] == '') {
                                $prjref_id = null;
                            } else {
                                $prjref_id = $prjref_idData[$j];
                            }


                            $jobRefData['prjref_id'] = $prjref_id;
                            $jobRefData['prj_id'] = $prj_id;
                            $jobRefData['job_id'] = $id;
                            $jobRefData['job_qty'] = $job_qtyData[$j];
                            $jobRefData['job_uom'] = $job_uomData[$j];

                            $jobRefData['job_startdate'] = $job_startdateData[$j];
                            $jobRefData['job_code'] = $job_codeData[$j];

                            $jobRefData['job_enddate'] = $job_enddateData[$j];
                            $jobRefData['job_materialcost'] = GTL_Common::setNumberFormat($job_materialcostData[$j]);
                            $jobRefData['job_materialsrp'] = GTL_Common::setNumberFormat($job_materialsrpData[$j]);
                            $jobRefData['job_totalmaterialcost'] = GTL_Common::setNumberFormat($job_totalmaterialcostData[$j]);
                            $jobRefData['job_totalmaterialsrp'] = GTL_Common::setNumberFormat($job_totalmaterialsrpData[$j]);
                            $jobRefData['job_remark'] = $job_remarkData[$j];
                            $jobRefData['ctr_id'] = $contractorIdData[$j];
                            $jobRefModel->save($jobRefData, 'prjref_id');
                            $j++;
                        }
                    }



                    //Load Quotation Image Model
                    $projectImageModel = new Model_Projectimages();
                    //Multiple Quotation Image Upload Logic
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    $i = 0;
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $fileName = '';
                            $folder = $this->config->UPLOAD_PATH . "project/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);

                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);

                            $thumb2 = PhpThumbFactory::create($folder . $fileName);
                            $thumb2->resize(200, 200);
                            $thumb2->save($folder . '/' . 'thumb_' . $fileName, 'jpg');

                            $projectImageData = Array();
                            $projectImageData['prj_id'] = $prj_id;
                            $projectImageData['prji_type'] = $postedData['imagetype'][$i];
                            $projectImageData['prji_notes'] = $postedData['prji_notes'][$i];
                            $projectImageData['prji_image'] = $fileName;
                            $projectImageModel->save($projectImageData, 'prji_id');
                        }
                        $i++;
                    }


                    $project_notes = $postedData['project_notes'];
                    if ($project_notes != '') {
                        //Insert project Notes
                        $projectNoteArray = Array();
                        $projectNoteArray['prj_id'] = $prj_id;
                        $projectNoteArray['prjn_notes'] = $project_notes;

                        if ($this->USER->role == 'ADMIN') {
                            $projectNoteArray['prjn_type'] = 1; //Admin Type 
                            $projectNoteArray['prjn_lgn_id'] = $this->USER->adm_id; //Customer id
                        } else {
                            $projectNoteArray['prjn_type'] = $this->USER->lgn_type; //Designer, Contractor or Customer
                            $projectNoteArray['prjn_lgn_id'] = $this->USER->usr_id; //Customer id
                        }
                        $projectNoteArray['prjn_createddate'] = date('Y-m-d H:i:s');

                        //Save Project Notes
                        $projectNotesModel->save($projectNoteArray, 'prjn_id');
                    }

                    if ($this->view->mode == "Add") {
                        $successmessage = "Project added successfully";
                    } else {
                        $successmessage = "Project updated successfully";
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'project', '');
                }
            }
        }

        $this->view->total_day_diff = $total_day_diff;
        $this->view->customerArray = $customerArray;
        $this->view->desginerArray = $desginerArray;
        
        $this->view->projectNotes = $projectNotes;
        $this->view->projectReference = $projectReference;
        $this->view->contractors = $contractors;
        $this->view->projectImages = $projectImages;
        $this->view->imageTypeArray = $imageTypeArray;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $projectForm;
        $indexUrl = $this->view->url(array('controller' => 'index', 'action' => 'index'), null, TRUE);
        $projectUrl = $this->view->url(array('controller' => 'project', 'action' => 'list'), null, TRUE);
        $this->view->breadcrumbs = array($indexUrl => "Home", $projectUrl => "Project", "" => $this->view->mode . " Project");
    }

    public function deleteprojectimageAction() {

        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $prji_id = $postedData['prji_id'];

            //Load project Image Model
            $projectImageModel = new Model_Projectimages();
            $data = $projectImageModel->fetchRow("prji_id = '" . $prji_id . "'");
            if ($data) {
                $projectImageModel->delete("prji_id = '" . $prji_id . "'");
                $folder = $this->config->UPLOAD_PATH . "project/";
                $image = $folder . $data->prji_image;
                $thumb_image = $folder . "thumb_" . $data->prji_image;
                if (file_exists($image)) {
                    @unlink($image);
                }
                if (file_exists($thumb_image)) {
                    @unlink($thumb_image);
                }
            }
        }
        exit;
    }

    //Function to give the data of individual job
    public function generatejobsearchAction() {
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            if ($postedData['type'] == 'job') {
                $job = Array(
                    'id' => '',
                    'code' => 'No such job available',
                    'uom' => '',
                    'costprice' => '0.00',
                    'srpprice' => '0.00'
                );
                $jobModel = new Model_Job();
                $jobArray = $jobModel->fetchJobs("`job_code` LIKE '%" . $postedData['search'] . "%'");
                $jsonArray = Array();
                if (count($jobArray) > 0) {
                    foreach ($jobArray as $_job) {
                        $job = Array(
                            'id' => $_job['job_id'],
                            'code' => $_job['job_code'],
                            'uom' => $_job['job_uom'],
                            'costprice' => $_job['job_materialcost'],
                            'srpprice' => $_job['job_materialsrp'],
                        );
                        $jsonArray[] = $job;
                    }
                } else {
                    $jsonArray[] = $job;
                }
                echo Zend_Json_Encoder::encode($jsonArray);
            }
        }
        exit;
    }

    public function deleteprojectreferenceAction() {
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $prjref_id = $postedData['prjref_id'];
            $prj_id = $postedData['prj_id'];

            //Load Model project reference
            $projectRefModel = new Model_Projectreference();
            $projectRefModel->delete("prjref_id = '" . $prjref_id . "'");

            //Load Model project
            $projectModel = new Model_Project();
            $projectData = $projectModel->fetchEntryById($prj_id);
            $projectRef = $projectData['PROJECT_REFERENCE'];

            $project = $projectData['PROJECT'];

            $totalCost = "0.00";
            if (count($projectRef) > 0) {
                foreach ($projectRef as $_ref) {
                    $totalCost += $totalCost;
                }
            }

            //Profit is calulated by the project total Selling price - TotalCost
            $profitLoss = $project['prj_sellingprice'] - $totalCost;

            if ($project['dsg_commision_type'] == 'percentage') {
                $dsg_commision = ($project['prj_sellingprice'] * $project['dsg_commision_percentage']) / 100;
            }
        }
        exit;
    }

}

?>
